import { Toast } from 'antd-mobile';
import React, { Component } from 'react';
import NavHeader from '../../components/NavHeader';
import { getLocation } from '../../utils';
import api from '../../utils/api';
import styles from './index.module.scss';
import './index.scss';

const labelStyle = {
  cursor: 'pointer',
  border: '0px solid rgb(255,0,0)',
  padding: '0px',
  whiteSpace: 'nowrap',
  fontSize: '12px',
  color: 'rbg(255,255,255)',
  textAlign: 'center'
};


export default class MyMap extends Component {
  state = {
    isShowHouseList: false,
    houseList: []
  };

  componentDidMount() {
    this.initMap();
  }

  async initMap() {
    const mapInfo = await getLocation();

    let map = new window.BMap.Map("container");
    this.map = map;
    // 创建地址解析器实例     
    let myGeo = new window.BMap.Geocoder();
    // 将地址解析结果显示在地图上，并调整地图视野    
    myGeo.getPoint(mapInfo.label, async (point) => {
      if (point) {
        map.centerAndZoom(point, 11);
        map.addOverlay(new window.BMap.Marker(point));
        map.addControl(new window.BMap.NavigationControl());
        map.addControl(new window.BMap.ScaleControl());

        this.renderOverlays(mapInfo.value);
      }
    },
      mapInfo.label);

    map.addEventListener('dragstart', () => {
      if (this.state.isShowHouseList) {
        this.setState({
          isShowHouseList: false
        });
      }
    });

  }

  async renderOverlays(id) {
    Toast.loading('加载中...');
    // 发送请求获取房源数据
    const res = await api.get('http://localhost:8080/area/map', {
      params: { id }
    });
    Toast.hide();

    let { type, nextZoom } = this.getTypeAndZoom();

    res.data.body.forEach((v, i) => {
      this.createOverlays(v, type, nextZoom);
    });
  }

  getTypeAndZoom() {
    const zoom = this.map.getZoom();
    let type = 'circle';
    let nextZoom = 0;

    if (10 <= zoom && zoom < 12) {
      nextZoom = 13;
    } else if (12 <= zoom && zoom < 14) {
      nextZoom = 15;
    } else if (14 <= zoom && zoom < 16) {
      type = "rect";
    }
    return { type, nextZoom };
  }

  createOverlays({ coord, count, label, value }, type, nextZoom) {
    if (type === 'circle') {
      this.createCircle(coord.longitude, coord.latitude, label, count, value, nextZoom);
    } else {
      this.createReact(coord.longitude, coord.latitude, label, count, value);
    }
  }



  createCircle(longitude, latitude, name, count, id, nextZoom) {
    const point = new window.BMap.Point(longitude, latitude); // 指定文本标注所在的地理位置
    let opts = {
      position: point,
      offset: new window.BMap.Size(-35, -35) // 设置文本偏移量
    };
    // 创建文本标注对象
    let label = new window.BMap.Label('', opts);
    // 自定义文本标注样式
    label.setStyle(labelStyle);
    label.setContent(`
                <div  class="${styles.bubble}">
                    <p class="${styles.name}">${name}</p>
                    <p >${count}套</p>
                </div>
            `);
    this.map.addOverlay(label);

    label.addEventListener('click', () => {
      this.map.setZoom(nextZoom);
      this.map.panTo(point);
      setTimeout(() => {
        this.map.clearOverlays();
      }, 0);
      this.renderOverlays(id);
    });
  }

  createReact(longitude, latitude, name, count, id) {
    const point = new window.BMap.Point(longitude, latitude); // 指定文本标注所在的地理位置
    let opts = {
      position: point,
      offset: new window.BMap.Size(-35, -35) // 设置文本偏移量
    };
    // 创建文本标注对象
    let label = new window.BMap.Label('', opts);
    // 自定义文本标注样式
    label.setStyle(labelStyle);
    label.setContent(`
    <div  class="${styles.rect}">
      <span class="${styles.houseName}">${name}</span>
      <span class="${styles.houseNum}" >${count}套</span>
      <i class="${styles.arrow}"></i>
    </div>
    `);
    this.map.addOverlay(label);

    label.addEventListener('click', (e) => {
      const target = e.changedTouches[0];
      this.map.panBy(window.innerWidth / 2 - target.clientX,
        (window.innerHeight - 330) / 2 - target.clientY
      );

      this.getHouseList(id);
    });
  }

  async getHouseList(id) {
    Toast.loading('加载中...');
    const res = await api.get('https://api-haoke-web.itheima.net/houses', {
      params: {
        cityId: id
      }
    });
    Toast.hide();
    this.setState({
      houseList: res.data.body.list,
      isShowHouseList: true
    });
  }

  render() {
    return (
      <div className='map'>
        <NavHeader>地图找房</NavHeader>
        <div id="container"></div>
        <div className={`${styles.houselist} ${this.state.isShowHouseList ? styles.show : ''}`}>
          <div className={styles.title}>
            房屋列表 <span className={styles.more}>更多房源</span>
          </div>

          {this.state.houseList.map((item) => (

            <div className={styles.houseItem} key={item.houseCode}>
              <div className={styles.imgWrap}>
                <img src={`http://localhost:8080${item.houseImg}`} alt="" />
              </div>

              <div className={styles.right}>
                <div className={styles.houseTitle}>
                  {item.title}
                </div>
                <div>
                  {item.desc}
                </div>
                <div className={styles.tags}>
                  {item.tags.map((tag, i) => (
                    <span key={tag} className={styles[`tag${i + 1}`]}>{tag}</span>
                  ))}
                </div>
                <div className="prices">
                  3000<span>元/月</span>
                </div>
              </div>
            </div>


          ))}
        </div>
      </div>
    );
  }
}
